<?php
/**
 * 品牌管理控制器
 * @author e5
 *
 */
class BrandController extends AuthController{
	private $db;
	public function __init(){
		parent::__init();
		$this->db = K("Brand");
	}
	/**
	 * 品牌列表
	 */
	public function index(){
		//处理分页
		$total = $this->db->count();
		$page = new Page($total,7);
		if ($total > 7){
			$pageData = $page->show();
		}else {
			$pageData = "";
		}
		//查询数据
		$bData = $this->db->limit($page->limit())->all();
		$this->assign("pageData",$pageData);
		$this->assign("bData",$bData);
		$this->display("brand");
	}
	/**
	 * 添加品牌
	 */
	public function add() {
		if (IS_POST){
			if (!$this->db->addBrand()) $this->error($this->db->error);
			$this->success("添加品牌成功",U("index"));
		}
		$this->display("addBrand");
	}
	/**
	 * 编辑品牌
	 */
	public function edit(){
		if (IS_POST){
			//获得原logo
			$bid = Q("post.bid",0,"intval");
			$logo = $this->db->field("blogo")->where("bid={$bid}")->find();
			//更新品牌数据
			if (!$this->db->editBrand()) $this->error("编辑品牌失败");
			//判断是否删除原logo
			if ($logo['blogo'] != $_POST['logo']){
				is_file($logo['blogo']) && unlink($logo['blogo']);
			}
			$this->success("编辑品牌成功",U("index"));
		}
		//获得原数据
		$bid = Q("get.bid",0,"intval");
		$bData = $this->db->where("bid={$bid}")->find();
		if (empty($bData)) $this->error("品牌不存在");
		$this->assign("bData",$bData);
		$this->display("editBrand");
	}
	/**
	 * 删除品牌
	 */
	public function del(){
		$bid = Q("get.bid",0,"intval");
		if ($bid == 0) $this->error("品牌不存在");
		//判断品牌中是否存在商品
		if (K("Goods")->where("vshop_brand_bid={$bid}")->count() > 0) $this->error("请先删除本品牌下的商品");
		//获得logo地址
		$logo = $this->db->field("blogo")->where("bid={$bid}")->find();
		if (empty($logo)) $this->error("品牌不存在");
		//删除品牌数据
		if ($this->db->where("bid={$bid}")->delete() != 1) $this->error("删除品牌失败");
		//删除logo文件
		is_file($logo['blogo']) && unlink($logo['blogo']);
		$this->success("删除品牌成功",U("index"));
	}
	/**
	 * 排序品牌
	 */
	public function setOrder(){
		$sortArr = Q("post.bsort");
		$cidArr = Q("post.bid");
		$temp = array();
		//组合数组
		foreach ($cidArr as $k=>$v){
			$temp[$k]['bid'] = $v;
			$temp[$k]['bsort'] = intval($sortArr[$k]);
		}
		//更新数据
		foreach ($temp as $v){
			$this->db->where("bid={$v['bid']}")->update(array("bsort"=>$v['bsort']));
		}
		$this->success("排序成功",U("index"));
	}
	/**
	 * 处理由uploadify上传的文件
	 */
	public function upload() {
		$upload = new Upload("Upload/BrandLogo");
		$file = $upload->upload();
		if (empty($file)){
			$this->ajax("上传失败");
		}else {
			$data = $file[0];
			$this->ajax($data);
		}
	}
}